package com.stone;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 统计服务器某个接口的访问次数
 */
public class AccessCount {

    private static ReentrantLock lock = new ReentrantLock();

    private static int accessCount;

    /**
     * 普通方法，会出现并发问题
     */
    public static  void access(){
        accessCount++;
        System.out.println(accessCount);
    }

    /**
     * 局部变量
     */
    public static void test(){
        int i = 1;
        accessCount+=i;

        System.out.println(accessCount);
    }


    private static ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<Integer>();

    public static void threadTest(){

        try {

            integerThreadLocal.set(accessCount++);
        }finally {
            integerThreadLocal.remove();
        }
        System.out.println(integerThreadLocal.get());

    }
    private static AtomicInteger atomicInteger=new AtomicInteger(0);

    public static void CASTest(){
        atomicInteger.addAndGet(accessCount++);
        System.out.println(atomicInteger.get());
    }

    public static synchronized void synchronizedTest(){

        accessCount++;
        System.out.println(accessCount);
    }

    public static void lockTest(){

        lock.lock();
        try {
            accessCount++;
            System.out.println(accessCount);
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        for (int i1 = 0; i1 < 100; i1++) {
            new Thread(new Runnable() {
                public void run() {
                    synchronizedTest();
                }
            }).start();
        }

    }
}
